define(['moment'], function (moment) {
    return ['$rootScope', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$timeout', '$mdDialog',
        function ($rootScope, $scope, $filter, $stateParams, config, $MMWService, $timeout, $mdDialog) {
            $scope.init = function () {
                $scope.bottom_mode = 'select_defectReason';
                $scope.data = {
                    dispose_user: config.cache.account,
                    pcs_list: []
                };
                $scope.barcode_no = '';
                $scope.item_list = [];
                $scope.reel_list = [];
                $scope.confirm_list = [];
                $scope.reel_group = 1;
                document.getElementById('barcode_no').focus();
                document.getElementById('barcode_no').select();
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            // QRCode輸入
            $scope.QRCodeScanner = function (type) {
                $scope.$root.OpenScanner({
                    after: function (result) {
                        if (type == 'second') {
                            $scope.secord_barcode = result.text;
                            SecondBarcodeSearch();
                        } else {
                            $scope.barcode_no = result.text;
                            $scope.search();
                        }
                    },
                    exception: function () {
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation: 'landscape'
                });
            };

            // barcode輸入
            $scope.input_barcode_no = function (event) {
                if (event.keyCode == 13) {
                    $scope.search();
                }
            };

            $scope.SecordbarcodeScan = function (event) {
                if (event.keyCode == 13) {
                    SecondBarcodeSearch();
                }
            };

            // 掃描序號
            $scope.search = function (content) {
                var barcode = $scope.barcode_no;
                $scope.barcode_no = '';
                if(!content){
                    $scope.data = {};
                    $scope.secondary_pcs_no = barcode;
                    $scope.hasRecall = false;
                    var content = {
                        input_no: barcode,
                        type:"7" // modify by Oliver for M#69746 7代表維修訊息，讓後端知道這是維修服務
                    }
                }
                if (content.input_no != '') {
                    $MMWService.sendToServer({
                        uri: 'ServicesSMT.Module_SMT.panel_info_get',
                        content: content,
                        success: function (data) {
                            if( +data.recall == 1){
                                $scope.hasRecall = true;
                                if(data.pcs_no && data.panel_no){
                                    $scope.data.pcs_no = data.pcs_no;
                                    $scope.data.panel_no = data.panel_no;
                                }
                                this.content.input_no = data.panel_no;
                                this.content.recall = data.recall;
                                $scope.search(this.content);
                            }else{
                                var _result = ValidatePCSStatus(data.pcs_list);
                                if (_result.error_msg == '') {
                                    if (_result.warring_msg == '') {
                                        $scope.pcs_item = data.pcs_list;
                                        $scope.data.pcs_list = data.pcs_list;
                                        $scope.data.mode = data.mode;
                                        $scope.data.op_no = data.op_no;

                                        $scope.data.panel_no = data.panel_no;
                                        if(!$scope.hasRecall){
                                           $scope.data.pcs_no = data.pcs_list.pcs_no; 
                                        }
                                        $scope.data.plot_no = data.lot_no;
                                        $scope.data.product_no = data.product_no;
                                        $scope.data.item_spec = data.item_spec;
                                        $scope.data.qty = data.pcs_count;
                                        $scope.data.machine_no = data.equipment_no;

                                        $scope.data.barcode = barcode;

                                        $scope.data.smt_op_seqname = data.smt_op_seqname;
                                        $scope.data.maintain_count = data.maintain_count;
                                        $scope.data.smt_op_seq = data.smt_op_seq;
                                        $scope.data.maintain_no = data.maintain_no;  
                                        if(data.reason_list.length!=0){//20200601不良原因可能為空 by Oliver
                                            $scope.item_list = data.reason_list;
                                        }
                                    } else {
                                        $scope.$root.showConfirm(_result.warring_msg, function (confirmDialog) {
                                            confirmDialog.hide();
                                            $scope.pcs_item = data.pcs_list[0];
                                            $scope.data.pcs_list = data.pcs_list;
                                            $scope.data.mode = data.mode;
                                            $scope.data.op_no = data.op_no;

                                            $scope.data.panel_no = data.panel_no;
                                            if(!$scope.hasRecall){
                                               $scope.data.pcs_no = data.pcs_list[0].pcs_no; 
                                            }
                                            $scope.data.plot_no = data.lot_no;
                                            $scope.data.product_no = data.product_no;
                                            $scope.data.item_spec = data.item_spec;
                                            $scope.data.qty = data.pcs_count;
                                            $scope.data.machine_no = data.equipment_no;
                                            $scope.data.barcode = barcode;

                                            $scope.item_list = data.reason_list;
                                            $scope.data.maintain_no = $scope.item_list[0].maintain_no;
                                        });
                                    };
                                } else {
                                    $scope.$root.showAlert(_result.error_msg);
                                };
                            }
                        }
                    });
                };
            };

            // 新增不良原因 (開窗)
            $scope.AddReason = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'tool_abnormal_reason_info_get',
                    key: 'reason_no',
                    header: [
                        { label: $filter('translate')('SMT16.list2.defect_reason_no'), code: 'reason_no' },
                        { label: $filter('translate')('SMT16.list2.defect_reason_name'), code: 'reason_name' }
                    ],
                    setCondition: function (conditions) {
                        conditions.push({ column_name: 'ReasonType', query_mode: '0', value: 'Product', merge_condition_model: 'AND' });
                        return conditions;
                    },
                    confirm: function (selectItem, dialog) {
                        var _temp = $filter('filter')($scope.item_list, { reason_no: selectItem.reason_no }, true);
                        if (_temp.length == 0) {
                            dialog.hide();
                            $scope.item_list.push({
                                reason_no: selectItem.reason_no,
                                reason_name: selectItem.reason_name,
                                defect_qty: 1
                            });
                        } else {
                            $scope.$root.showAlert($filter('translate')('SMT16.msg.reason_duplidate'));
                        }
                    }
                });
            };

            // 切換成品序號
            $scope.ChangePCS = function (pcs) {
                $scope.pcs_item = pcs;
            }

            // 刪除不良原因項目
            $scope.removeRow = function (item) {
                $scope.item_list.splice($scope.item_list.indexOf(item), 1);
            };

            // 刪除更換零件項目
            $scope.removeComponent = function (item) {
                if (item.pcs_resource_guid == $filter('translate')('SMT16.origin')) {
                    $scope.$root.showConfirm($filter('translate')('SMT16.msg.delete_record'), function (dialog) {
                        $scope.reel_list.splice($scope.reel_list.indexOf(item), 1);
                        dialog.hide();
                    })
                } else {
                    $scope.reel_list.splice($scope.reel_list.indexOf(item), 1);
                }
            };

            // 確定送修
            $scope.confirm = function () {
                if ($scope.item_list.length > 0) {
                    let ever_fix = $scope.item_list.every(function (item, index, array) {//判斷當中是否有送修ok的項目
                        return item.repair_status == "true";
                    })
                    if (ever_fix) {
                        //$scope.$root.showSelect({
                        //    label : 'type_name',
                        //    code : 'type_no',
                        //    //selectCode : item.column_name,
                        //    list : [
                        //        {type_name:$filter('translate')('SMT16.completed_type.type_4'), type_no:4},
                        //        {type_name:$filter('translate')('SMT16.completed_type.type_5'), type_no:5},
                        //        {type_name:$filter('translate')('SMT16.completed_type.type_6'), type_no:6}
                        //    ],
                        //    confirm : function(selectItem, dialog){
                        //        dialog.hide();
                        //        panel_info_set_process(selectItem.type_no);
                        //        $scope.$root.showToast($filter('translate')('SMT16.msg.maintaining_completed'));
                        //        document.getElementById('barcode_no').focus();
                        //        document.getElementById('barcode_no').select();
                        //    }
                        //});
                        openDialog();
                    } else {
                        $scope.$root.showAlert($filter('translate')('SMT16.msg.fix_process_hasnt_finished_yet'));
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('SMT15.msg.reason_list_empty'));
                }
            }

            // 維修狀態按鈕 true/false
            $scope.slide_btn = function (item) {
                item.slideBtn = [item.slideBtn == 'true' ? 'false' : 'true'];
                if (item.slideBtn == 'true') {
                    item.repair_status = 'true'
                } else {
                    item.repair_status = 'false'
                }
            }

            function ValidatePCSStatus(pcs_list) {
                var _result = { error_msg: '', warring_msg: '' };
                for (var i = 0; i < pcs_list.length; i++) {
                    if (pcs_list[i].status != 'R') {
                        _result.warring_msg += $filter('translate')('SMT16.msg.seq_not_ng', pcs_list[i].pcs_no);
                        break;
                    }
                };
                return _result;
            }

            function SecondBarcodeSearch() {
                if ($scope.bottom_mode == 'select_defectReason') {
                    var _temp = $filter('filter')($scope.item_list, { reason_no: $scope.secord_barcode }, true);
                    if (_temp.length == 0) {
                        $MMWService.pageNumberInfoGet({
                            page_mode: 'tool_abnormal_reason_info_get',
                            query_condition_info: [
                                { column_name: 'ReasonType', query_mode: '0', value: 'Product', merge_condition_model: 'AND' },
                                { column_name: 'ReasonNo', query_mode: '0', value: $scope.secord_barcode, merge_condition_model: 'AND' },
                            ]
                        }, function (itemList) {
                            if (itemList.length > 0) {
                                $scope.secord_barcode = '';
                                $scope.item_list.push({
                                    reason_no: itemList[0].reason_no,
                                    reason_name: itemList[0].reason_name,
                                    defect_qty: 1
                                });
                            } else {
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            };
                        });
                    } else {
                        $scope.secord_barcode = '';
                        $scope.$root.showAlert($filter('translate')('SMT16.msg.reason_duplidate'));
                    }
                } else {
                    if($scope.hasRecall){
                        $scope.secondary_pcs_no = $scope.data.panel_no;
                    }
                    $MMWService.sendToServer({
                        uri: 'ServicesSMT.Module_SMT.reel_change_info_get',
                        content: {
                            pcs_no:$scope.secondary_pcs_no,
                            lot_no:$scope.data.plot_no,
                            eqp_no:$scope.data.machine_no,
                            reel_no:$scope.secord_barcode
                        },
                        success: function (data) {
                            if(data!=''){
                                data.forEach(function(item){
                                    if(!item.pcs_resource_guid){
                                        item.qty = 1;
                                    }
                                    item.group = $scope.reel_group;
                                    item.position_no = '';
                                    $scope.reel_list.unshift(item);
                                });
                                $scope.reel_group++;
                                $scope.secord_barcode = '';
                            }else{
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            }
                        }
                    });
                }
            }

            function panel_info_set_process(type) {
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.panel_info_set_process',
                    content: {
                        op_no: $scope.data.op_no,
                        equipment_no: $scope.data.machine_no,
                        plot_no: $scope.data.plot_no,
                        panel_no: $scope.hasRecall? $scope.data.panel_no : $scope.data.barcode,
                        pcs_count: $scope.data.qty,
                        maintain_no: $scope.data.maintain_no,
                        dispose_user: $scope.data.dispose_user,
                        type: type,
                        smt_op_seq:$scope.data.smt_op_seq,
                        mode: $scope.data.mode,
                        pcs_list: $scope.reel_list,
                        reason_list: $scope.item_list
                    },
                    success: function (data) {
                        $scope.bottom_mode = 'select_defectReason';
                        $scope.data = {
                            dispose_user: $scope.data.dispose_user,
                            pcs_list: []
                        };
                        $scope.item_list = [];
                        $scope.reel_list = [];
                        $scope.pcs_item = undefined;
                        $scope.reel_group = 0;
                    }
                });
            }

            var openDialog = function (feedback) {
                $mdDialog.dialog('module/moduleSMT/program/SMT16/SMT16_Confirm.tmp.html',
                    function (dialog) {
                        return {
                            css_url: 'module/moduleSMT/program/SMT16/SMT16.css',
                            confirm_type: [
                                '4', '5', '6'
                            ],
                            status: '0',
                            type:'4',
                            smt_op_seq: '',
                            changeStatus: function (type,status) {
                                dialog.status = status;
                                dialog.type = type;
                            },
                            loadSMTOPSeq: function () {
                                if ($scope.data.plot_no != "") {
                                    $MMWService.showQueryListPNIG({
                                        page_mode: 'smt_op_seq_info_get',
                                        key: 'smt_op_seq',
                                        header: [
                                            { label: $filter('translate')('SMT15.list3.smt_op_seq'), code: 'smt_op_seq' },
                                            { label: $filter('translate')('SMT15.list3.smt_op_seq_name'), code: 'smt_op_seq_name' },
                                            { label: $filter('translate')('SMT15.list3.description'), code: 'description' }
                                        ],
                                        setCondition: function (conditions) {
                                            conditions.push({ column_name: 'c.BASELOTNO', query_mode: '0', value: $scope.data.plot_no, merge_condition_model: 'AND' });
                                            return conditions;
                                        },
                                        confirm: function (selectItem, dialog1) {
                                            dialog.smt_op_seq = selectItem.smt_op_seq;
                                        }
                                    });
                                } else {
                                    $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                }
                            },
                            back: function () {
                                dialog.hide();
                            },
                            confirm: function () {
                                $scope.data.smt_op_seq = dialog.smt_op_seq;
                                panel_info_set_process(dialog.type);
                                dialog.hide();
                                $scope.$root.showToast($filter('translate')('SMT16.msg.maintaining_completed'));
                                document.getElementById('barcode_no').focus();
                                document.getElementById('barcode_no').select();
                            }
                        };
                    }
                );
            };
        }
    ];
});
